package com.easyjava.builder;

import com.easyjava.bean.Constants;
import com.easyjava.bean.FieldInfo;
import com.easyjava.bean.TableInfo;
import com.easyjava.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @projectName: work-space
 * @author: Li
 * @description:
 */

public class BuildServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(BuildServiceImpl.class);

    public static void execute(TableInfo tableInfo) {
        File folder = new File(Constants.PATH_SERVICE_IMPL);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        String interfaceName = tableInfo.getBeanName() + Constants.SUFFIX_SERVICE;
        String classImplName = tableInfo.getBeanName() + "ServiceImpl";
        String mapperName = tableInfo.getBeanName() + Constants.SUFFIX_MAPPERS;
        String mapperBeanName = StringUtils.lowerCaseFirstLetter(mapperName);
        File poFile = new File(folder, classImplName + ".java");

        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        try {
            os = new FileOutputStream(poFile);
            osw = new OutputStreamWriter(os, "UTF-8");
            bw = new BufferedWriter(osw);
            bw.write("package " + Constants.PACKAGE_SERVICE_IMPL + ";");
            bw.newLine();
            bw.newLine();

            bw.write("import java.util.List;");
            bw.newLine();
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_PO + "." + tableInfo.getBeanName() + ";");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_QUERY + "." + tableInfo.getBeanQueryName() + ";");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_VO + ".PaginationResultVo;");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_QUERY + ".SimplePage;");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_ENUMS + ".PageSizeEnum;");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_SERVICE + "." + interfaceName + ";");
            bw.newLine();
            bw.write("import " + Constants.PACKAGE_MAPPERS + "." + mapperName + ";");

            bw.newLine();
            bw.write("import org.springframework.stereotype.Service;");
            bw.newLine();
            bw.newLine();
            bw.write("import javax.annotation.Resource;");

            bw.newLine();
            bw.newLine();
            BuildComment.createClassComment(bw, tableInfo.getTableName() + " ServiceImpl");
            bw.newLine();
            bw.write("@Service(\"" + StringUtils.lowerCaseFirstLetter(interfaceName) + "\")");
            bw.newLine();
            bw.write("public class " + classImplName + " implements " + interfaceName + " {");
            bw.newLine();
            bw.newLine();

            bw.write("\t@Resource");
            bw.newLine();
            bw.write("\tprivate " + mapperName + "<" + tableInfo.getBeanName() + ", " + tableInfo.getBeanQueryName() + "> " + mapperBeanName + ";");
            bw.newLine();
            bw.newLine();

            BuildComment.createFieldComment(bw, "根据条件查询列表");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic List<" + tableInfo.getBeanName() + "> findListByParam(String tableName, " + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".selectList(tableName, query);");
            } else {
                bw.write("\tpublic List<" + tableInfo.getBeanName() + "> findListByParam(" + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".selectList(query);");
            }
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            BuildComment.createFieldComment(bw, "根据条件查询数量");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic Integer findCountByParam(String tableName, " + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".selectCount(tableName, query);");
            } else {
                bw.write("\tpublic Integer findCountByParam(" + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".selectCount(query);");
            }
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            BuildComment.createFieldComment(bw, "分页查询");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic PaginationResultVo<" + tableInfo.getBeanName() + "> findListByPage(String tableName, " + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\tInteger count = this.findCountByParam(tableName, query);");
                bw.newLine();
                bw.write("\t\tInteger pageSize = query.getPageSize() == null ? PageSizeEnum.SIZE15.getSize() : query.getPageSize();");
                bw.newLine();
                bw.write("\t\tSimplePage page = new SimplePage(query.getPageNo(), count, pageSize);");
                bw.newLine();
                bw.write("\t\tquery.setSimplePage(page);");
                bw.newLine();
                bw.write("\t\tList<" + tableInfo.getBeanName() + "> list = this.findListByParam(tableName, query);");
            } else {
                bw.write("\tpublic PaginationResultVo<" + tableInfo.getBeanName() + "> findListByPage(" + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\tInteger count = this.findCountByParam(query);");
                bw.newLine();
                bw.write("\t\tInteger pageSize = query.getPageSize() == null ? PageSizeEnum.SIZE15.getSize() : query.getPageSize();");
                bw.newLine();
                bw.write("\t\tSimplePage page = new SimplePage(query.getPageNo(), count, pageSize);");
                bw.newLine();
                bw.write("\t\tquery.setSimplePage(page);");
                bw.newLine();
                bw.write("\t\tList<" + tableInfo.getBeanName() + "> list = this.findListByParam(query);");
            }
            bw.newLine();
            bw.write("\t\tPaginationResultVo<" + tableInfo.getBeanName() + "> result = new PaginationResultVo<>(count, page.getPageSize(), page.getPageNo(), list, page.getPageTotal());");
            bw.newLine();
            bw.write("\t\treturn result;");

            bw.newLine();

            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            BuildComment.createFieldComment(bw, "新增");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic Integer add(String tableName, " + tableInfo.getBeanName() + " bean) {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".insert(tableName, bean);");
            } else {
                bw.write("\tpublic Integer add(" + tableInfo.getBeanName() + " bean) {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".insert(bean);");
            }
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            BuildComment.createFieldComment(bw, "批量新增");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic Integer addBatch(String tableName, List<" + tableInfo.getBeanName() + "> listBean) {");
                bw.newLine();
                bw.write("\t\tif (listBean == null || listBean.isEmpty()) {");
                bw.newLine();
                bw.write("\t\t\treturn 0;");
                bw.newLine();
                bw.write("\t\t}");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".insertBatch(tableName, listBean);");
            } else {
                bw.write("\tpublic Integer addBatch(List<" + tableInfo.getBeanName() + "> listBean) {");
                bw.newLine();
                bw.write("\t\tif (listBean == null || listBean.isEmpty()) {");
                bw.newLine();
                bw.write("\t\t\treturn 0;");
                bw.newLine();
                bw.write("\t\t}");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".insertBatch(listBean);");
            }
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            BuildComment.createFieldComment(bw, "批量新增/更新");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic Integer addOrUpdateBatch(String tableName, List<" + tableInfo.getBeanName() + "> listBean) {");
                bw.newLine();
                bw.write("\t\tif (listBean == null || listBean.isEmpty()) {");
                bw.newLine();
                bw.write("\t\t\treturn 0;");
                bw.newLine();
                bw.write("\t\t}");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".insertOrUpdateBatch(tableName, listBean);");
            } else {
                bw.write("\tpublic Integer addOrUpdateBatch(List<" + tableInfo.getBeanName() + "> listBean) {");
                bw.newLine();
                bw.write("\t\tif (listBean == null || listBean.isEmpty()) {");
                bw.newLine();
                bw.write("\t\t\treturn 0;");
                bw.newLine();
                bw.write("\t\t}");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".insertOrUpdateBatch(listBean);");
            }
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            Map<String, List<FieldInfo>> keyIndexMap = tableInfo.getKeyIndexMap();
            for (Map.Entry<String, List<FieldInfo>> entry : keyIndexMap.entrySet()) {
                List<FieldInfo> keyFieldInfoList = entry.getValue();
                int index = 0;
                StringBuilder methodName = new StringBuilder();
                StringBuilder paramsName = new StringBuilder();
                StringBuilder params = new StringBuilder();
                if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                    paramsName.append("String tableName, ");
                    params.append("tableName, ");
                }
                for (FieldInfo fieldInfo : keyFieldInfoList) {
                    index++;
                    methodName.append(StringUtils.upperCaseFirstLetter(fieldInfo.getPropertyName()));
                    if (index < keyFieldInfoList.size()) {
                        methodName.append("And");
                    }
                    paramsName.append(fieldInfo.getJavaType() + " " + fieldInfo.getPropertyName());
                    params.append(fieldInfo.getPropertyName());
                    if (index < keyFieldInfoList.size()) {
                        paramsName.append(", ");
                        params.append(", ");
                    }
                }
                bw.newLine();
                BuildComment.createFieldComment(bw, "根据" + methodName + "查询");
                bw.newLine();
                bw.write("\tpublic " + tableInfo.getBeanName() + " get" + tableInfo.getBeanName() + "By" + methodName + "(" + paramsName + ") {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".selectBy" + methodName + "(" + params + ");");
                bw.newLine();
                bw.write("\t}");
                bw.newLine();
                bw.newLine();

                BuildComment.createFieldComment(bw, "根据" + methodName + "更新");
                bw.newLine();
                bw.write("\tpublic Integer update" + tableInfo.getBeanName() + "By" + methodName + "(" + tableInfo.getBeanName() + " bean, " + paramsName + ") {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".updateBy" + methodName + "(bean, " + params + ");");
                bw.newLine();
                bw.write("\t}");
                bw.newLine();
                bw.newLine();

                BuildComment.createFieldComment(bw, "根据" + methodName + "删除");
                bw.newLine();
                bw.write("\tpublic Integer delete" + tableInfo.getBeanName() + "By" + methodName + "(" + paramsName + ") {");
                bw.newLine();
                bw.write("\t\treturn " + mapperBeanName + ".deleteBy" + methodName + "(" + params + ");");
                bw.newLine();
                bw.write("\t}");
                bw.newLine();
            }
            bw.newLine();

            BuildComment.createFieldComment(bw, "根据条件更新");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic void updateByQuery(String tableName, " + tableInfo.getBeanName() + " bean , " + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\tStringTools.checkParam(query);");
                bw.newLine();
                bw.write("\t\t" + mapperBeanName + ".updateByQuery(tableName, bean, query);");
            } else {
                bw.write("\tpublic void updateByQuery(" + tableInfo.getBeanName() + " bean , " + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\tStringTools.checkParam(query);");
                bw.newLine();
                bw.write("\t\t" + mapperBeanName + ".updateByQuery(bean, query);");
            }
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            BuildComment.createFieldComment(bw, "根据条件删除");
            bw.newLine();
            if (tableInfo.getTableName().equals(Constants.SPLIT_TABLE_NAME)) {
                bw.write("\tpublic void deleteByQuery(String tableName, " + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\tStringTools.checkParam(query);");
                bw.newLine();
                bw.write("\t\t" + mapperBeanName + ".deleteByQuery(tableName, query);");
            } else {
                bw.write("\tpublic void deleteByQuery(" + tableInfo.getBeanQueryName() + " query) {");
                bw.newLine();
                bw.write("\t\tStringTools.checkParam(query);");
                bw.newLine();
                bw.write("\t\t" + mapperBeanName + ".deleteByQuery(query);");
            }
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();

            bw.write("}");
            bw.flush();

        } catch (Exception e) {
            logger.error("生成ServiceImpl文件失败", e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
